/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pe.edu.pucp.cpnc.mm.manager;

import pe.edu.pucp.cpnc.mm.bean.Map;
import java.util.Stack;

/**
 *
 * @author Luis
 */
public class SaveStateManager {
    private final stateStack states;
    private int currState;
    
    private class stateStack extends Stack<Map>{
        private final int maxSize;
        
        public stateStack(int size){
            super();
            maxSize = size;
        }
        
        @Override
        public Map push(Map m){
            if(size() == maxSize )
                remove(0);
            else
                currState++;
            
            return super.push(m);
        }
        
        public void clearNewerStates(){
            while(size()-1>currState){
                pop();
            } 
        }
        
    }
    
    public SaveStateManager(int maxStates, Map initState){
        states = new stateStack(maxStates);
        currState=-1;
        states.push(new Map(initState));
    }
    
    public void pushState(Map oMap){
        Map state = new Map(oMap);
        
        //User has used the undo function
        if(currState<states.size()-1)
            states.clearNewerStates();
        
        states.push(state);
        
    }
    
    public Map undo(){
        if(currState>=1){
            currState--;
            return new Map(states.get(currState));
        }else
            return null;
        
    }
    
    public Map redo(){
        if(currState==states.size()-1)
            return null;
        else{
            currState++;
            return new Map(states.get(currState));
        }
    }
}